package com.west.xu.sms.util;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.Sign;
import cn.hutool.crypto.asymmetric.SignAlgorithm;

import java.util.Base64;

public class SignUtils {

    /**
     * @Author PangFeiHu
     * @Description 根据数据获取签名
     * @Date 18:38 2020/11/18
     * @Param [privateKey 私钥, publicKey 公钥, data 数据, algorithm 类型]
     * @return java.lang.String
     **/
    public static String getSignKey(String privateKey,String publicKey,String data,String algorithm){
        Sign sign = getSign(algorithm,privateKey,publicKey);
        byte[] signed = sign.sign(data.getBytes());
        return Base64.getEncoder().encodeToString(signed);
    }

    /**
     * @Author PangFeiHu
     * @Description  根据算法和公钥私钥 获取验签 处理器
     * @Date 18:37 2020/11/18
     * @Param  gignType 算法
     *         privateKey 私钥
     *         publicKey  公钥
     * @return
     **/
    public static Sign getSign(String gignType,String privateKey,String publicKey){
        SignAlgorithm signAlgorithm = SignAlgorithm.valueOf(gignType);
        return SecureUtil.sign(signAlgorithm,privateKey,publicKey);
    }
    /**
     * @Author PangFeiHu
     * @Description 验签
     * @Date 18:36 2020/11/18
     * @Param  privateKey 私钥
     *         publicKey 公钥
     *         data 数据
     *         signData 渠道传递过来的key
     *         algorithm 算法
     * @return  void
     **/
    public static boolean sign(String privateKey,String publicKey,String data,String signData,String algorithm){
        Sign sign = getSign(algorithm,privateKey,publicKey);
        return sign.verify(data.getBytes(),Base64.getDecoder().decode(signData));
    }
}
